package com.redstar.HappyRefresh.manage;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.redstar.HappyRefresh.authority.Authority;
import com.redstar.HappyRefresh.pojo.*;
import com.redstar.HappyRefresh.service.RoleService;
import com.redstar.HappyRefresh.service.UserRoleService;
import com.redstar.HappyRefresh.service.UserService;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/user")
public class UserManage { // 用户管理端

    @Resource
    private UserService userService;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private RoleService roleService;

    @GetMapping("/list")
    @Authority("admin:user:list")
    public Result list() { // 查询所有的用户信息
        return Result.succeed().data(userService.list());
    }

    @GetMapping("/page")
    @Authority("admin:user:page")
    public Result list(BasePage basePage, @RequestParam(required = false) String email) { // 分页模糊查询用户角色信息，用于搜索
        // 根据邮箱信息分页模糊查询用户信息，当name为null时，查询所有用户信息
        IPage<User> userPage = userService.page(basePage.page(), new LambdaQueryWrapper<User>().like(!ObjectUtils.isEmpty(email), User::getEmail, email));
        // 查询用户角色信息，key为userId
        Map<Long, List<UserRole>> userRoleMap = userRoleService.list().stream().collect(Collectors.groupingBy(UserRole::getUserId));
        // 查询角色信息，key为roleId，value为roleName
        Map<Long, String> roleMap = roleService.list().stream().collect(Collectors.toMap(Role::getId, Role::getName));
        // key为userId，value为角色名称
        Map<Long, Set<String>> userRoleNamemap = new HashMap<>();
        // 将用户角色信息封装到map中
        userRoleMap.forEach((uId, rIds) -> {
            Set<String> roles = new HashSet<>();
            for (UserRole rId : rIds) {
                // 将指定用户对应的所有角色名称封装到set中
                roles.add(roleMap.get(rId.getRoleId()));
            }
            userRoleNamemap.put(uId, roles);
        });
        // 将用户信息和角色信息组装到User对象中
        for (User user : userPage.getRecords()) {
            user.setRoleName(userRoleNamemap.get(user.getId()));
        }
        return Result.succeed().data(userPage.getRecords()).count(userPage.getTotal());
    }
}
